package com.lc1993929.mvc.servlet;

import com.lc1993929.actions.Action;
import com.lc1993929.actions.ActionManager;
import com.lc1993929.actions.ActionMapping;
import com.lc1993929.actions.ActionMappingManager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by LiuChang on 2017/5/8.
 */
public class ActionServlet extends HttpServlet {

    private ActionMappingManager actionMappingManager = null;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据actionName获取一个ActionMapping，通过ActionMappingManager获取ActionMapping
        try {
            ActionMapping actionMapping = actionMappingManager.getActionMapping(this.getActionName(req));
            //获取className
            Action action = ActionManager.createAction(actionMapping.getClassName());
            //执行业务逻辑
            String resultName = action.execute(req, resp);
            //转向结果显示页面
            if (null == resultName) {
                resp.sendError(404, "未配置Action对应的result元素！");
                return;
            }
            //根据resultName获取result
            String result = actionMapping.getResult(resultName);

            //重定向结果页
            resp.sendRedirect(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getActionName(HttpServletRequest req) {
        //获取URI
        String uri = req.getRequestURI();
        //获取上下文路径
        String contextPath = req.getContextPath();
        //截取上下文路径，获取ActionPath
        String actionPath = uri.substring(contextPath.length());
        //获取ActionName
        String actionName = actionPath.substring(1, actionPath.lastIndexOf(".")).trim();

        return actionName;
    }


    //webserver自动加载框架配置文件
    @Override
    public void init(ServletConfig config) throws ServletException {
        //读取配置信息
        String configStr = config.getInitParameter("config");
        //可以读取多个配置文件
        String[] fileNames = null;

        //判断配置文件是否配置
        if (null == configStr || "".equals(configStr)) {
            fileNames = new String[]{"myframework.xml"};
        } else {
            fileNames = configStr.split(",");
        }

        //根据配置文件产生
        this.actionMappingManager = new ActionMappingManager(fileNames);
    }
}
